package br.consultorio.digital.control;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import br.consultorio.digital.R;
import br.consultorio.digital.modelo.ModelMedico;
import br.consultorio.digital.modelo.entidade.Medico;

public class MedicoListar extends ListActivity implements TextWatcher {
	protected static final int VOLTAR = 1, AgendaMenu = 2,
			AgendaDataListar = 3, MedicoListar = 4;
	private EditText edtmedico;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.medico);

		edtmedico = (EditText) findViewById(R.idMedico.edtMedico);
		edtmedico.addTextChangedListener(this);

		buscaTodosMedico();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent it = new Intent();
		it.putExtra("id_medico",
				((Medico) l.getAdapter().getItem(position)).getId_medico());
		it.putExtra("tx_medico",
				((Medico) l.getAdapter().getItem(position)).getNm_medico());
		setResult(MedicoListar, it);
		finish();
	}

	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (v.getId()) {
		case R.idMedico.edtMedico:
			if (!edtmedico.getText().toString().equals("")) {
				buscarMedico(edtmedico.getText().toString());
			} else {
				buscaTodosMedico();
			}
			break;
		}
		return false;
	}

	private void buscarMedico(String text) {
		ModelMedico pModel = new ModelMedico(this);
		pModel.tratarConsultaMedico(edtmedico.getText().toString());
	}

	private void buscaTodosMedico() {
		ModelMedico adModel = new ModelMedico(this);
		adModel.tratarConsultaTodos();
	}

	public void afterTextChanged(Editable s) {
	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (start + count > 0) {
			buscarMedico(edtmedico.getText().toString());
		} else {
			buscaTodosMedico();
		}
	}
}
